<?php

namespace app\sys\controller;

use think\Db;
use think\Image;

// 后台 商品管理
class Product extends Admin
{
    // 商品列表
    public function index()
    {
        $admin_info = session('admin_info');
        if (request()->isAjax()) {
            $name = input('param.name', '');
            $brand = input('param.brand', '');
            $type = input('param.type', '');
            $classify = input('param.classify', '');
            $sold_out = input('param.sold_out', '');
            $page = input('param.page', 1);
            $page = $page <= 0 ? 1 : $page;
            $limit = input('param.limit', 20);
            $order_field = input('param.field', '');
            $order_type = input('param.order', 0);
            $query = [];
            // 供应商只能看到自己的
            if (6 == $admin_info['permission']) {
                $query['admin_id'] = $admin_info['id'];
            }
            if ($name) {
                $query['name'] = ['like', $name];
            }
            if ($brand) {
                $query['brand'] = $brand;
            }
            if ($type) {
                $query['type'] = $type;
            }
            if ('' != $classify) {
                $query['classify'] = intval($classify);
            }
            if ('' != $sold_out) {
                $query['sold_out'] = intval($sold_out);
            }
            $order = ['ct' => -1];
            if ($order_field && $order_type) {
                $order[$order_field] = 'asc' == $order_type ? 1 : -1;
            }
            $list = Db::name('product')->where($query)->page($page)->limit($limit)->order($order)->select();
            foreach ($list as $key => $value) {
                if ($value['type']) {
                    $type_info = Db::name('type')->find($value['type']);
                    $list[$key]['type_name'] = $type_info['name'];
                }
                if ($value['brand']) {
                    $brand_info = Db::name('brand')->find($value['brand']);
                    $list[$key]['brand_name'] = $brand_info['name'];
                }
                $list[$key]['ct'] = date('Y-m-d H:i:s', $value['ct']);
            }
            $count = Db::name('product')->where($query)->count();

            return success(['data' => $list, 'count' => $count]);
        }

        $brand_list = Db::name('brand')->field('id,name')->select();
        $type_list = Db::name('type')->field('id,name')->select();

        return view('index', ['page' => $page, 'limit' => $limit, 'name' => $name, 'brand_list' => $brand_list, 'type_list' => $type_list]);
    }

    // 商品编辑
    public function productEdit()
    {
        $admin_info = session('admin_info');
        $id = input('param.id', '');
        if (request()->isPost()) {
            $data = input('param.', '');
            $row = [];
            $id = $data['id'];
            if ($id) {
                $find = Db::name('product')->where('id', $id)->find();
                if (6 == $admin_info['permission'] && $find['admin_id'] != $admin_info['id']) {
                    return error('只能修改自己的产品');
                }
            }
            $row['type'] = strval($data['type']);
            if (!$row['type'] || 24 != strlen($row['type'])) {
                return error('请选择商品分类');
            }
            $row['brand'] = strval($data['brand']);
            if (!$row['brand'] || 24 != strlen($row['brand'])) {
                return error('请选择商品品牌');
            }

            $brand_info = Db::name('brand')->find($row['brand']);
            $type_info = Db::name('type')->find($row['type']);
            $row['model'] = subString(strval($data['model']), 20);
            $row['name'] = $brand_info['name'].' '.$row['model'].' '.$type_info['name']; //.$data['version'].'版'; //品牌+型号+类别 //先隐藏 +版本
            $row['tag'] = $data['tag'];
            $row['info'] = $data['info'];
            $row['weight'] = $data['weight'];
            // 宣传段子
            $row['passage'] = trim($data['passage']);
            // 供应商不能上架 只能新增
            if ($id) {
                $row['sold_out'] = isset($find['sold_out']) ? $find['sold_out'] : 1;
            } else {
                $row['sold_out'] = 1;
            }
            if (6 == $admin_info['permission']) {
                $row['admin_id'] = $admin_info['id'];
            }
            $row['classify'] = 0;
            $row['order'] = intval($data['order']);
            $row['pics'] = $data['pics'];
            $row['pic'] = strval($data['pics'][0]);
            //存在修改 不存在添加
            Db::name('product')->where('id', $id)->update($row, ['upsert' => true]);
            // 添加新商品时让开通自动上架的帮会 自动上架
            if (!$id) {
                $last_id = Db::name('product')->getLastInsID();
                $new_find = Db::name('product')->find($last_id);
                if ($new_find) {
                    autoPutaway([$new_find]);
                }
            }

            return success();
        }
        if (6 != $admin_info['permission'] && !$id) {
            return error('只有供应商才能添加产品');
        }

        $data = Db::name('product')->find($id);
        $brand_list = Db::name('brand')->field('id,name')->select();
        $type_list = Db::name('type')->field('id,name')->select();

        return view('productEdit', ['info' => $data, 'brand_list' => $brand_list, 'type_list' => $type_list]);
    }

    // 商品规格编辑（价格设定）
    public function specificationsEdit()
    {
        $admin_info = session('admin_info');
        if ($admin_info['permission'] < 6) {
            return error('你的权限不够');
        }
        $data = input('param.', '');
        $id = $data['id'];
        if (request()->isPost()) {
            $row = [];
            if (!$data['specifications'] || 0 == count($data['specifications'])) {
                return error('至少添加一项规格');
            }
            foreach ($data['specifications'] as $key => $value) {
                if (!$value['title']) {
                    return error('请填写第'.($key + 1).'项规格名称');
                }
                if (0 == $value['stock']) {
                    return error('['.$value['title'].']的库存没设置');
                }
                if (6 == $admin_info['permission'] && 0 == $value['real_supply']) {
                    return error('['.$value['title'].']的供货价格没设置');
                }
                if (6 != $admin_info['permission'] && 0 == $value['supply_price']) {
                    return error('['.$value['title'].']的供货价格没设置');
                }
                if (6 != $admin_info['permission'] && 0 == $value['retail_price']) {
                    return error('['.$value['title'].']的零售价格没设置');
                }
            }
            $flag = false;
            foreach ($data['specifications'] as $key => $value) {
                $data['specifications'][$key]['stock'] = intval($value['stock']);
                $data['specifications'][$key]['code'] = strval($value['code']);
                if (6 == $admin_info['permission']) {
                    $data['specifications'][$key]['real_supply'] = round($value['real_supply'], 2);
                } elseif (10 == $admin_info['permission']) {
                    //这个帮会价是上架的时候帮主设置的最低帮会价格
                    $data['specifications'][$key]['gang_price'] = round($value['gang_price'], 2);
                    $data['specifications'][$key]['real_supply'] = round($value['real_supply'], 2);
                    $data['specifications'][$key]['supply_price'] = round($value['supply_price'], 2);
                    $data['specifications'][$key]['retail_price'] = round($value['retail_price'], 2);
                    $data['specifications'][$key]['suggest_price'] = round($value['retail_price'], 2);
                    if ($data['specifications'][$key]['supply_price'] <= $data['specifications'][$key]['real_supply']) {
                        return error('['.$value['title'].']的帮主供货价必须大于真实供货价');
                    }
                    if ($data['specifications'][$key]['gang_price'] <= $data['specifications'][$key]['supply_price']) {
                        return error('['.$value['title'].']的帮主供货价必须大于帮会价');
                    }
                    if ($data['specifications'][$key]['retail_price'] <= $data['specifications'][$key]['gang_price']) {
                        return error('['.$value['title'].']的建议零售价必须大于帮会价');
                    }
                }
            }
            // todo 写消息队列
            // 如果新的帮主供货价 改高了 把将之前低于新价的帮会价格也改到新价
            // 帮会价的下限应该是帮主供货价+加价 再算帮会最终供货价 再update
            $product_info = Db::name('product')->find($id);
            if (0 == $product_info['sold_out']) {
                foreach ($data['specifications'] as $key => $value) {
                    $title_flag = false;
                    foreach ($product_info['specifications'] as $k => $v) {
                        if ($value['title'] == $v['title']) {
                            $title_flag = true;
                            // 针对供应商整合其他价格
                            if (6 == $admin_info['permission']) {
                                $data['specifications'][$key]['gang_price'] = round($v['gang_price'], 2);
                                $data['specifications'][$key]['supply_price'] = round($v['supply_price'], 2);
                                $data['specifications'][$key]['retail_price'] = round($v['retail_price'], 2);
                                $data['specifications'][$key]['suggest_price'] = round($v['retail_price'], 2);
                            }

                            if ($value['real_supply']>$v['real_supply']) {
                                $flag = true;
                            } else {
                                continue;
                            }
                            $sp = round($value['supply_price'], 2);
                            $suggest_price = round($value['suggest_price'], 2);
                            $gang_product = Db::name('gang_product')->where(['specifications' => $value['title'], 'product_id' => $id])->select();
                            foreach ($gang_product as $gp) {
                                $gang_info = Db::name('gang')->find($gp['gang_id']);
                                $gang_type = Db::name('gang_type')->find($gang_info['type_id']);
                                if ($gang_type) {
                                    $current_raise = round($gang_type['raise_price_list'][$product_info['brand']][$product_info['type']], 2);
                                    if (!$current_raise) {
                                        $current_raise = round($gang_type['raise_price'], 2);
                                    }
                                } else {
                                    $current_raise = 0;
                                }
                                $new_lowest_gang_price = round($sp * round($current_raise / 100 + 1, 4), 2);
                                if ($gp['gang_price'] < $new_lowest_gang_price) {
                                    $flag = true;
                                    $gang_product = Db::name('gang_product')->where('id', $gp['id'])->update(['gang_price' => $new_lowest_gang_price, 'retail_price' => $suggest_price]);
                                }
                            }
                        }
                    }
                    if (!$title_flag) {
                        $flag = true;
                    }
                }
            }
            
            // 货商改高了供货价需要下架 加规格也下架 改规格也下架   其他操作如加减库存改、商品名称等操作 不下架
            if ($flag || count($product_info['specifications']) < count($data['specifications'])) {
                $row['sold_out'] = 1;
            }
            $row['specifications'] = $data['specifications'];

            $row['tag_price'] = round($data['tag_price'], 2);
            $row['sales'] = intval($data['sales']);

            Db::name('product')->where('id', $id)->update($row);

            return success();
        }

        $data = Db::name('product')->find($id);

        return view('specificationsEdit', ['info' => $data]);
    }

    // 商品删除
    public function productDel()
    {
        if (request()->isPost()) {
            $admin_info = session('admin_info');
            if ($admin_info['permission'] < 6) {
                return error('你的权限不够');
            }
            $id = input('param.id', '');
            Db::name('product')->delete($id);

            return success();
        }

        return error();
    }

    // 商品上下架关闭（供应商只能下架 不能上架[提交新商品然后管理员设置价格再上架]）
    public function productSoldOut()
    {
        if (request()->isPost()) {
            $admin_info = session('admin_info');
            if ($admin_info['permission'] < 6) {
                return error('你的权限不够');
            }
            $id = input('param.id', '');
            $sold_out = input('param.sold_out', '');
            $sold_out = 'true' == $sold_out ? 0 : 1;
            if (6 == $admin_info['permission'] && 0 == $sold_out) {
                return error('供应商只能下架，不能上架');
            }
            if ($admin_info['permission'] > 6 && 0 == $sold_out) {
                //上架前检查所有价格是否都填写了
                $product_info = Db::name('product')->find($id);
                foreach ($product_info['specifications'] as $value) {
                    if (0 == $value['stock']) {
                        return error('['.$value['title'].']的库存没设置');
                    }
                    if (0 == $value['supply_price']) {
                        return error('['.$value['title'].']的供货价格没设置');
                    }
                    if (0 == $value['retail_price']) {
                        return error('['.$value['title'].']的零售价格没设置');
                    }
                }
                // 修改所有低于最低供应价的帮会价 todo 写消息队列
                foreach ($product_info['specifications'] as $value) {
                    $gang_product = Db::name('gang_product')->where(['specifications' => $value['title'], 'product_id' => $id])->select();
                    if ($gang_product) {
                        $sp = round($value['supply_price'], 2);
                        $suggest_price = round($value['suggest_price'], 2);
                        foreach ($gang_product as $gp) {
                            $gang_info = Db::name('gang')->find($gp['gang_id']);
                            $gang_type = Db::name('gang_type')->find($gang_info['type_id']);
                            if ($gang_type) {
                                $current_raise = round($gang_type['raise_price_list'][$product_info['brand']][$product_info['type']], 2);
                                if (!$current_raise) {
                                    $current_raise = round($gang_type['raise_price'], 2);
                                }
                            } else {
                                $current_raise = 0;
                            }
                            $new_lowest_gang_price = round($sp * round($current_raise / 100 + 1, 4), 2);
                            if (!$gp['gang_price'] || $gp['gang_price'] < $new_lowest_gang_price) {
                                $gang_product = Db::name('gang_product')->where('id', $gp['id'])->update(['gang_price' => $new_lowest_gang_price, 'retail_price' => $suggest_price]);
                            }
                        }
                    }
                }
                // 自动上架
                autoPutaway([$product_info]);
            }
            Db::name('product')->where('id', $id)->update(['sold_out' => $sold_out]);

            return success();
        }

        return error();
    }

    // 商品分类列表
    public function productType()
    {
        $name = input('param.name', '');
        $page = input('param.page', 1);
        $page = $page <= 0 ? 1 : $page;
        $limit = input('param.limit', 20);
        $order_field = input('param.field', '');
        $order_type = input('param.order', 0);
        if (request()->isAjax()) {
            $query = [];
            if ($name) {
                $query['name'] = ['like', $name];
            }
            $order = ['sort' => 1];
            if ($order_field && $order_type) {
                $order[$order_field] = 'asc' == $order_type ? 1 : -1;
            }
            $list = Db::name('type')->where($query)->page($page)->limit($limit)->order($order)->select();
            $count = Db::name('type')->where($query)->count();

            return success(['data' => $list, 'count' => $count]);
        }

        return view('productType');
    }

    // 商品分类编辑
    public function productTypeEdit()
    {
        if (request()->isPost()) {
            $data = input('param.', '');
            $row = [];
            $row['sort'] = intval($data['sort']);
            $row['name'] = strval($data['name']);
            $id = $data['id'];
            unset($data['id']);
            //存在修改 不存在添加
            Db::name('type')->where('id', $id)->update($data, ['upsert' => true]);

            return success();
        }

        $id = input('param.id', '');
        $data = Db::name('type')->find($id);

        return view('productTypeEdit', $data);
    }

    // 商品品牌列表
    public function productBrand()
    {
        $name = input('param.name', '');
        $page = input('param.page', 1);
        $page = $page <= 0 ? 1 : $page;
        $limit = input('param.limit', 20);
        $order_field = input('param.field', '');
        $order_type = input('param.order', 0);
        if (request()->isAjax()) {
            $query = [];
            if ($name) {
                $query['name'] = ['like', $name];
            }
            $order = ['sort' => 1];
            if ($order_field && $order_type) {
                $order[$order_field] = 'asc' == $order_type ? 1 : -1;
            }
            $list = Db::name('brand')->where($query)->page($page)->limit($limit)->order($order)->select();
            $count = Db::name('brand')->where($query)->count();

            return success(['data' => $list, 'count' => $count]);
        }

        return view('productBrand');
    }

    // 商品品牌编辑
    public function productBrandEdit()
    {
        if (request()->isPost()) {
            $data = input('param.', '');
            $row = [];
            $row['sort'] = intval($data['sort']);
            $row['name'] = strval($data['name']);
            $row['pic'] = strval($data['pic']);
            $id = $data['id'];
            unset($data['id']);
            //存在修改 不存在添加
            Db::name('brand')->where('id', $id)->update($data, ['upsert' => true]);

            return success();
        }

        $id = input('param.id', '');
        $data = Db::name('brand')->find($id);

        return view('productBrandEdit', $data);
    }

    // 上传图片
    public function uploadPic()
    {
        $admin_info = session('admin_info');
        if ($admin_info['permission'] < 6) {
            return error('你的权限不够');
        }
        if (!request()->isPost()) {
            return error('只支持post');
        }
        $width = input('post.width', 800);
        $height = input('post.height', 640);
        $file = request()->file('file');
        if ($file) {
            // 移动到服务器的上传目录 并且使用md5规则 最大5M
            $info = $file->validate(['size' => 5242880, 'ext' => 'jpg,png'])->rule('md5')->move(ROOT_PATH.'public'.DS.'uploads');
            if ($info) {
                $image = Image::open(ROOT_PATH.'public'.DS.'uploads/'.$info->getSaveName());
                $image->thumb($width, $height)->save(ROOT_PATH.'public/uploads/'.$info->getSaveName());

                return success(config('file_domain').'uploads/'.$info->getSaveName());
            } else {
                return error('上传失败 '.$file->getError());
            }
        }

        return error('缺少参数：file');
    }

    // 售后说明
    public function aftersale()
    {
        $admin_info = session('admin_info');
        if (6 != $admin_info['permission']) {
            return error('你的权限不够');
        }
        if (request()->isPost()) {
            $data = input('param.', '');
            $row = [];
            $row['admin_id'] = strval($admin_info['id']);
            $row['info'] = $data['aftersale'];
            $row['ct'] = time();
            //存在修改 不存在添加
            Db::name('product_after_sale_intro')->where('admin_id', $row['admin_id'])->update($row, ['upsert' => true]);

            return success();
        }
        $data = Db::name('product_after_sale_intro')->where('admin_id', $admin_info['id'])->find();

        return view('aftersale', $data);
    }
}
